<template>
  <div style="height: 100%;">
      <div style="height: 100%;" v-show="doType=='show'" id="show_html" class="show_note_html"  @click="vHmtlClick" v-html="content"/>
      <div v-show="doType=='editor'" style="height: 100%;">
        <script  id="editor" type="text/plain" ref="myUEditor"></script>
      </div>
  </div>
</template>

<script>
    import Vue from 'vue'
    import {getFileIcon,uploadFile,download} from '@/api/dl'

    export default {
        name: 'UEditor',
        props: {
          content:{
              type: String,
              default: ''
          },
          doType: {
            type:String,
            default: 'show'
          },
          nnTextType: {//绑定云记的类型字段
            'type': Number, //
          },
          tableId:null,
        },
        watch: {
          'content': {
              handler: function(){
                  //渲染数据
                  // this.readye();
              }
          },
          'doType': {
            handler: function(){
              if(this.doType=='editor'&&this.nnTextType==1){
                this.init();
              }
            }
          }
        },
        data () {
            return {
                previewConfig:{
                    img:["jpg", "jpeg", "gif", "png", "bmp"],
                },
                editor: null,
                tempContent:null,
                myConfig: {
                  // 如果需要上传功能,找后端小伙伴要服务器接口地址
                  // serverUrl: this.$config.baseUrl + 'ueditor/ueditorConfig',
                  serverUrl: Vue.prototype.webUrl+'ueditor/ueditorConfig',
                  // 你的UEditor资源存放的路径,相对于打包后的index.html
                  UEDITOR_HOME_URL: '/ueditor/',
                  toolbars: [
                        ['undo', 'redo','removeformat','formatmatch',// 撤销\重做  删除格式\格式刷
                            'paragraph','fontfamily','fontsize',//  标题\字体\字体大小
                            'link','unlink',//超链接
                            'bold', 'italic', 'underline', 'strikethrough',
                            'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify',//对齐方式
                            'inserttable',//表格
                            'insertcode',//代码
                            'insertimage','simpleupload','attachment',//上传相关  多图上传\单图上传\附件上传
                            'insertvideo', //视频
                            '|','source'//源码
                        ]
                    ],
                  wordCount:false,
                  autoHeightEnabled:true,// 编辑器不自动被内容撑高
                  initialFrameWidth:'100%',
                  initialFrameHeight:'100%',
                  elementPathEnabled:false,
                  autoFloatEnabled:true,// 工具栏是否可以浮动
                  enableAutoSave: true,// 关闭自动保存
                  catchRemoteImageEnable: true, //设置是否抓取远程图片
                  initialStyle:'body{font-size:12px;}'
                },
            }
        },
        created(){
            window.f_download=download;
        },
        methods:{
            /**
             * v-html单击事件监控
             * @param e
             */
            vHmtlClick(e){
                let className =e.target.className;
                if(className.indexOf("annexFile_a")!=-1){
                    download(e.target.getAttribute("url"),e.target.getAttribute("fileName"));
                }
            },
            insertValue(annex,type){
                let value="";
                if(type==1){//插入为预览
                    let simg=new Set(this.previewConfig.img);
                    if(simg.has(annex.annexFile.saf_file_type)){
                        value= `<br/><img src="${Vue.prototype.webUrl+annex.annexFile.saf_file_path}" alt="${annex.sa_show_name}" title="${annex.sa_show_name}" />`;
                    }
                }else{//2或其他插入为附件
                    value= `<p><img src="/${getFileIcon(annex.annexFile.saf_file_type)}"><a class="annexFile_a" title="${annex.sa_show_name}"  url="${Vue.prototype.webUrl+annex.annexFile.saf_file_path}" fileName="${annex.sa_show_name}" target="_blank">${annex.sa_show_name}</a></p>`;
                }

                this.editor.focus()
                this.editor.execCommand('inserthtml', value);
            },
            init(){
                const that = this;
                this.editor = window.UE.getEditor('editor',that.myConfig);
                //服务请求都带上表id，说明是那张表的业务（上传图片）
                this.editor.ready(function() {
                    //提交时附带的额外参数
                    that.editor.execCommand('serverparam',{
                        'tableId':that.tableId,  //云记内码
                        'f_upload':function (file,callback) {
                            uploadFile(file,{
                                tableId:that.tableId,
                                workCode:1,
                                objName:0
                            },function (p,md5,o) {
                                if(p==100){
                                    if(callback)callback(o,Vue.prototype.webUrl);
                                }
                            });
                        },
                    });

                /*                //图片和文件存入OSS中
                    that.editor._bkGetActionUrl = that.editor.getActionUrl;
                    that.editor.getActionUrl = function(action) {
                        console.log(action);
                        if (action == 'uploadimage' || action == 'uploadfile') {
                            console.log("上传！！");
                            return ;
                            // return '${path}/web/ueuploadimageoss!ueUploadImgaeOSS';  //此处改需要把图片上传到哪个Action（Controller）中
                        } else {
                            return that.editor._bkGetActionUrl.call(this, action);
                        }
                    };*/


                });

                //渲染数据
                this.readye()
                /*            //失去焦点
                this.editor.addListener("blur",function(a,b){
                  if(that.content != that.getUEContent()){
                    console.log("内容修改，提交")
                    that.$emit('change',that.getUEContent());
                  }else{
                    console.log("内容没修改")
                  }
                });*/
            },
            //渲染数据
            readye(){
              let that = this;
              this.editor.ready(function() {
                  that.editor.setContent(that.content?that.content:"");
                  that.tempContent = that.content;
              })
            },
            getContentHtml(){
              return this.editor.getContentHtml();
            },
            getUEContent(){
                let uecontent = this.editor.getContent();
                return uecontent;
            },
            getContentTxt(){
                let getContentTxt = this.editor.getContentTxt();
                return getContentTxt;
            },
        }
    }
</script>
